﻿
''' <summary>
''' Provides a base class for task implementations.
''' </summary>
Public MustInherit Class BaseTask
    Implements Interfaces.ITask

    Private _Id As Guid
    Private _IsCompleted As Boolean
    Private _Exception As Exception

    Public Event Completed(ByVal sender As Object, ByVal e As System.EventArgs) Implements Interfaces.ITask.Completed

    Public Sub New()
        _Id = Guid.NewGuid
    End Sub

    Public ReadOnly Property Id() As System.Guid Implements Interfaces.ITask.Id
        Get
            Return _Id
        End Get
    End Property

    Public ReadOnly Property IsCompleted() As Boolean Implements Interfaces.ITask.IsCompleted
        Get
            Return _IsCompleted
        End Get
    End Property

    Protected ReadOnly Property Exception() As Exception
        Get
            Return _Exception
        End Get
    End Property

    Public Overridable Sub Run() Implements Interfaces.ITask.Run
        If IsAsync Then
            Try
                PerformOperation()
            Catch ex As Exception
                SetException(ex)
                SetCompleted()
            End Try
        Else
            PerformOperation()
            SetCompleted()
        End If
    End Sub

    Public MustOverride Sub WaitCompleted() Implements Interfaces.ITask.WaitCompleted

    Public MustOverride ReadOnly Property IsAsync() As Boolean Implements Interfaces.ITask.IsAsync

    Protected MustOverride Sub PerformOperation()

    ''' <summary>
    ''' Sets an exception on the task. This method should be called when an exception
    ''' occures during task execution.
    ''' </summary>
    Protected Overridable Sub SetException(ByVal ex As Exception)
        _Exception = ex
    End Sub

    ''' <summary>
    ''' Sets the task to completed.
    ''' </summary>
    Protected Overridable Sub SetCompleted()
        _IsCompleted = True
        Kernel.Logger.Log("TaskScheduler", TraceEventType.Information, "Task {0} completed.", Id)
    End Sub
End Class